package jh.com.jhappbf.assay;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.weight.query.SelectActivity;


public class AssayAdd extends AbActivity implements OnClickListener {
    private ImageView mPhoto;//拍摄的照片
    private String mPhotoInfo = "";//把照片转换成字符串上传
    private String mPhotoName;
    private String mAssayId;//编号


    private EditText mPlateNumber;//化验编号
    private EditText mCargoName;//货名
    private EditText mPrice;//单价
    private EditText mKouZa;//扣杂
    private EditText mKouShui;//扣水

    private final int GET_PLATENUM_REQUEST_CODE = 0X0001;

    //	private final int GETSPEC = 0x0001;
    private final int GETCARGONAME = 0X0002;
//    private final int GETSENDER = 0X0003;
//    private final int GETRECEIVER = 0X0004;
    private final int TAKEPHOTO = 0X0005;

    //	private String mSaverId="";
//    private String mTarget = "";
    //	private String mNet ="0";
//	private String mBalance = "0";
//    private String mCompute = "";
    //    private LinkedHashMap<String, String> mTargetAlias = new LinkedHashMap<>();
//    private LinkedHashMap<String, EditText> mTargetTxt = new LinkedHashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.assay_add_activity);
        AbTitleBar mAbTitleBar = this.getTitleBar();
//        LayoutParams params=new LinearLayout.LayoutParams(200, 50);
//        mAbTitleBar.setLayoutParams(params);
        mAbTitleBar.setMinimumHeight(50);
        mAbTitleBar.setTitleText("添加化验");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);

        initView();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        TextView assayId = findViewById(R.id.assay_assayId_txt);
        TextView plateNum = findViewById(R.id.assay_plateNum_txt);
        TextView mao = findViewById(R.id.assay_mao_txt);
        TextView pi = findViewById(R.id.assay_pi_txt);

        Intent intent = getIntent();
        mAssayId = intent.getStringExtra("assayId");
        String id="编号:" + mAssayId;
        assayId.setText(id);
        String num="车号:" + intent.getStringExtra("plateNum");
        plateNum.setText(num);
        String maoZhong="毛重:" + intent.getStringExtra("mao");
        mao.setText(maoZhong);
        String piZhong="皮重:" + intent.getStringExtra("pi");
        pi.setText(piZhong);

        ImageView mSearchName = findViewById(R.id.assay_search_cargoname);
        mSearchName.setOnClickListener(this);

        Button mCamera = findViewById(R.id.assay_add_camera);
        mCamera.setOnClickListener(this);
        mPhoto = findViewById(R.id.assay_add_image);
        mPrice = findViewById(R.id.assay_price_edit);
        mKouZa = findViewById(R.id.assay_value_edit);
        mKouShui = findViewById(R.id.assay_koushui_edit);
//        mAssayResult= (EditText) findViewById(R.id.assay_result_edit);
//        mAssayDeucation = (EditText) findViewById(R.id.assay_weight_value_edit);

//        mPrice.addTextChangedListener(new TextWatcher() {
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count,
//                                          int after) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if(mCompute.equals("D"))
//                {
//                    mKouZa.setText(s);
//                }
//            }
//        });
        mPlateNumber = findViewById(R.id.assay_num_edit);
        mCargoName = findViewById(R.id.assay_cargoname_edit);
//		mInputLayout =  (LinearLayout) findViewById(R.id.assay_input_layout);
        Button mBtnOk = findViewById(R.id.assay_btn_ok);
        mBtnOk.setOnClickListener(this);
        Button mRefreshOk = findViewById(R.id.assay_btn_refresh);
        mRefreshOk.setOnClickListener(this);
//		initAssayId();
    }


    /**
     * 刷新
     */
    private void refreshInput() {

        mCargoName.setText("");
        mPrice.setText("");
        mKouZa.setText("0");
        mKouShui.setText("0");
        mPhoto.setImageBitmap(null);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.assay_add_camera://拍照
                takePhoto();
                break;
            case R.id.assay_btn_ok://确定
                setAssay();
                break;
            case R.id.assay_btn_refresh://刷新
                refreshInput();
                break;
            case R.id.assay_search_img://选择车号
                //	selectPlateNum();

                getFieldValue("id", GET_PLATENUM_REQUEST_CODE);
                break;
            case R.id.assay_search_cargoname://选择货名

//			Log.e("wwh", "assay_search_cargoname点击事件");
                getFieldValue("cargoname", GETCARGONAME);
                break;
            default:
                break;
        }
    }

    /**
     * 拍照并显示
     */
    private void takePhoto() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mPhotoName = System.currentTimeMillis() + ".jpg";

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    Environment.getExternalStorageDirectory() + "/jinheng", mPhotoName)));
            startActivityForResult(intent, TAKEPHOTO);

        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    this.getFilesDir().getAbsolutePath() + "/jinheng", mPhotoName)));
            startActivityForResult(intent, TAKEPHOTO);
        }

    }

    /**
     * 保存化验结果
     */
    private void setAssay(){
        String kouShui = String.valueOf(mKouShui.getText());
        if (kouShui.length() == 0) {
            AbToastUtil.showToast(this, "扣水不能为空!");
            return;
        }
        String kouZa = String.valueOf(mKouZa.getText());
        if (kouZa.length() == 0) {
            AbToastUtil.showToast(this, "扣杂不能为空!");
            return;
        }
        String price = String.valueOf(mPrice.getText());
        if (price.length() == 0) {
            AbToastUtil.showToast(this, "单价不能为空!");
            return;
        }
        String name = String.valueOf(mCargoName.getText());
        if (name.length() == 0) {
            AbToastUtil.showToast(this, "货名不能为空!");
            return;
        }

        AbLoadDialogFragment mDialogFragment = AbDialogUtil.showLoadDialog(AssayAdd.this, R.mipmap.ic_load, "添加中,请稍等...");
        mDialogFragment.setCancelable(false);

        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        String methodName = "addAssay";
        param.add("assaynum");
        param.add("cargoname");
        param.add("price");
        param.add("kouza");
        param.add("koushui");
        param.add("image");
        param.add("user");

        value.add(mAssayId);
        value.add(mCargoName.getText().toString());
        value.add(mPrice.getText().toString());
        value.add(mKouZa.getText().toString());
        value.add(mKouShui.getText().toString());
        value.add(mPhotoInfo);
        value.add(State.mName);

        Listener<String> listener = response -> {

//                Log.e("wwh", "AssayAdd    onResponse: " + response);
            AbDialogUtil.removeDialog(AssayAdd.this);
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String result = obj.optString("result");
                if ("true".equals(result)) {
                    refreshInput();
                }
                String memo = obj.optString("memo");
                AbToastUtil.showToast(AssayAdd.this, memo);

                finish();
            }
        };

        ErrorListener errorListener = error -> {
//                Log.e("wwh", "onErrorResponse: " + "网络请求异常");
            AbDialogUtil.removeDialog(AssayAdd.this);
            AbToastUtil.showToast(AssayAdd.this, "网络请求异常，添加失败!");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(webService);
    }
//	/**
//	 * 选择化验编号
//	 */
//	private void selectPlateNum()
//	{
//		Intent i = new Intent(AssayAdd.this,AssayPlatenumSelect.class);
//		startActivityForResult(i, GET_PLATENUM_REQUEST_CODE);
//	}

    /**
     * 获取字段值
     */
    private void getFieldValue(String field, int value) {
        Intent i = new Intent(AssayAdd.this, SelectActivity.class);
        i.putExtra("flag", field);
        startActivityForResult(i, value);
    }

    //把bitmap转换成字符串
    public static String bitmapToString(Bitmap bitmap) {
        String string;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        byte[] bytes = baos.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    public static Bitmap stringToBitmap(String string) {
        // OutputStream out;
        Bitmap bitmap;
        try {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }

    public static Bitmap zoomImage(Bitmap bigImage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bigImage.getWidth();
        float height = bigImage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bigImage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }


    public static Bitmap compressImage(Bitmap image) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            int options = 90;

            while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                baos.reset(); // 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                if (options > 10) {
                    options -= 10;// 每次都减少10
                }
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中

            Bitmap bitmap = BitmapFactory.decodeStream(bais, null, null);// 把ByteArrayInputStream数据生成图片

            baos.close();

            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿，获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//		Log.e("wwh", requestCode+"");
        if (requestCode == TAKEPHOTO&&resultCode==RESULT_OK) {
            //	Bitmap bitmap = (Bitmap) data.getExtras().get("data");

            Bitmap bitmap = BitmapFactory.decodeFile(Environment.
                    getExternalStorageDirectory().getPath() + "/jinheng/" + mPhotoName);
            //		mPhoto.setImageBitmap(bitmap);
            //		Bitmap upbitmap=zoomImage(bitmap, bitmap.getWidth()/80, bitmap.getHeight()/80);
            //		Bitmap upbitmap=compressImage(bitmap);
//				Bitmap upbitmap=getSmallBitmap(Environment.
//						getExternalStorageDirectory().getPath()+"/jinheng/img/"+mPhotoName);
//				Bitmap upbitmap2=compressImage(upbitmap);
            Bitmap upBitmap = zoomImage(bitmap, bitmap.getWidth() / 4, bitmap.getHeight() / 4);
            mPhoto.setImageBitmap(bitmap);
            mPhotoInfo = bitmapToString(upBitmap);
//				System.out.println(mPhotoInfo);
//				Log.e("wwh", mPhotoInfo);
        }

        if (data != null) {
            if (requestCode == GET_PLATENUM_REQUEST_CODE) {
//				mSaverId = data.getStringExtra("id");
                String mPlatenum = data.getStringExtra("result");
                mPlateNumber.setText(mPlatenum);
//				mcargoname = data.getStringExtra("cargoname");
//				mTarget = data.getStringExtra("target");
//				mNet = data.getStringExtra("net");
                //if(mNet.length() == 0) mNet = "0";
//				mBalance = data.getStringExtra("balance");
                //if(mBalance.length() ==0) mBalance="0";
//				mCompute = data.getStringExtra("compute");
//				mPlateNumber.setText(mPlatenum);
//				mCargoName.setText(mcargoname);
//				makeView(mTarget);
            } else if (requestCode == GETCARGONAME) {
                String value = data.getStringExtra("result");
                mCargoName.setText(value);
            }
//			else if(requestCode == TAKEPHOTO){
//			//	Bitmap bitmap = (Bitmap) data.getExtras().get("data");
//
//				Bitmap bitmap=BitmapFactory.decodeFile(Environment.
//						getExternalStorageDirectory().getPath()+"/"+mPhotoName);
//				mPhoto.setImageBitmap(bitmap);
//
//				Log.e("wwh", bitmap.toString());
//			}
        }
    }

//    private void makeView(String target)
//    {
//        if(target.length() == 0) return;
//        mTargetAlias.clear();
//        mTargetTxt.clear();
//        String[] arr =target.split("#");
//        for (String item : arr) {
//            String[] arr1 = item.split("@");
//            if(arr1.length > 1)
//            {
//                if(!mTargetAlias.keySet().contains(arr1[0]) && arr1[0].length() > 0 && arr1[1].length() > 0)
//                {
//                    if(arr1[0].equals("A")||arr1[0].equals("R")||arr1[0].equals("S") ||arr1[0].equals("备注") )
//                    {
//                        continue;
//                    }
//                    mTargetAlias.put(arr1[0], arr1[1]);
//                }
//            }
//        }


//		Iterator iterator = mTargetAlias.entrySet().iterator();
//		mInputLayout.removeAllViews();
//		while(iterator.hasNext())
//		{
//			Map.Entry<String,String> entry =  (Entry<String, String>) iterator.next();
//			String key = entry.getKey();
//			String value = entry.getValue();
//
//			LinearLayout layout = new LinearLayout(AssayAdd.this);
//			LayoutParams param =new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//			int paddingValue = PixAndDpUtil.dp2px(2, AssayAdd.this);
//			layout.setPadding(paddingValue, paddingValue, paddingValue, paddingValue);
//			layout.setOrientation(1);
//			layout.setLayoutParams(param);
//
//			EditText edit = new EditText(AssayAdd.this);
//			edit.setHint("填写"+value);
//			int edtiPadding = PixAndDpUtil.dp2px(8, AssayAdd.this);
//			edit.setPadding(edtiPadding, edtiPadding, edtiPadding, edtiPadding);
//			layout.addView(edit);
//			mInputLayout.addView(layout);
//			mTargetTxt.put(key, edit);
//		}
//    }
}
